<template>

<!--  <h2>账号管理</h2>-->
  <br>
  <div align="left">
    <div>
      账号:
      <vxe-input v-model="搜索_账号" placeholder="模糊搜索账号" @keypress.native.enter="搜索账号列表"  class="my-domain"></vxe-input>
      设备:
      <vxe-input v-model="搜索_设备" placeholder="搜索设备" @keypress.native.enter="搜索账号列表" class="my-domain"></vxe-input>
      多区:
      <inputselect v-model:value="搜索_多区" v-model:list="多区数组" @keypress.native.enter="搜索账号列表"></inputselect>
      标记:
      <inputselect v-model:value="搜索_标记" v-model:list="标记数组" @keypress.native.enter="搜索账号列表"></inputselect>
      分配:
      <inputselect v-model:value="搜索_分配" :list="[{label:'全部',number:0},{label:'已分配',number:0},{label:'未分配',number:0}]" @keypress.native.enter="搜索账号列表"></inputselect>
      <span>
        账号状态:
        <inputselect v-model:value="搜索_账号状态" v-model:list="登录状态数组" @keypress.native.enter="搜索账号列表"></inputselect>
      </span>
      <span>
        区服状态:
        <inputselect v-model:value="搜索_区服状态" v-model:list="区服状态数组" @keypress.native.enter="搜索账号列表"></inputselect>
      </span>
<!--      <button type="button" class="vxe-button type&#45;&#45;button theme&#45;&#45;primary" @click="搜索账号列表">-->
<!--        <span class="vxe-button&#45;&#45;content">搜索</span>-->
<!--      </button>-->
    </div>

    <br/>
    <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" @click="刷新当前页" v-loading="加载中"><i class="layui-icon layui-icon-refresh"></i>刷新当前页</button>
    <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" @click="删除选中"><i class="layui-icon layui-icon-delete"></i>(批量)删除选中</button>
    <vxe-button size="small" status="info" transfer>
      <template #default>
        <button type="button" class="layui-btn layui-btn-sm">账号管理</button>
      </template>
      <template #dropdowns>
        <p>
          <router-link to='/plsczh'>
            <vxe-button type="text" content="导入账号"></vxe-button>
          </router-link>
        </p>
        <p>
          <vxe-button type="text" content="导出勾选账号" @click="导出到文档"></vxe-button>
        </p>
        <!-- <vxe-button type="text" content="一键清除重复"></vxe-button> -->
        <!-- <vxe-button type="text" content="清除当前列表"></vxe-button> -->
      </template>
    </vxe-button>

    <vxe-button size="small" status="info" transfer>
      <template #default>
        <button type="button" class="layui-btn layui-btn-sm">批量修改(选中)</button>
      </template>
      <template #dropdowns>
        <vxe-button type="text" content="修改标记" @click="批量修改_标记"></vxe-button>
        <vxe-button type="text" content="设定设备名2" @click="批量修改_设备名2"></vxe-button>
        <vxe-button type="text" content="启动分配" @click="批量修改_启动分配"></vxe-button>
        <vxe-button type="text" content="取消分配" @click="批量修改_取消分配"></vxe-button>
        <vxe-button type="text" content="恢复账号状态" @click="批量修改_恢复账号状态"></vxe-button>
      </template>
    </vxe-button>

    <vxe-button size="small" status="info" transfer>
      <template #default>
        <button type="button" class="layui-btn layui-btn-sm">批量多区设置</button>
      </template>
      <template #dropdowns>
        <vxe-button type="text" content="清空多区分配" value="11" @click="清空多区分配"></vxe-button>
        <vxe-button type="text" content="移除指定区分配" @click="移除指定区分配"></vxe-button>
        <vxe-button type="text" content="开启指定区分配" @click="开启关闭指定区($event)" value="1"></vxe-button>
        <vxe-button type="text" content="关闭指定区分配" @click="开启关闭指定区($event)" value="2"></vxe-button>
        <vxe-button type="text" content="开启全部区分配" @click="开启关闭_全部区($event)" value="1"></vxe-button>
        <vxe-button type="text" content="关闭全部区分配" @click="开启关闭_全部区($event)" value="2"></vxe-button>
        <vxe-button type="text" content="分配多区" @click="分配多区_拼接"></vxe-button>
      </template>
    </vxe-button>
    <span style="color:#cc3333"> 【操作步骤】 1：设定设备；2：分配多区（至少分配一个服区）；3：启动分配；</span>
  </div>


  <vxe-pager background v-model:current-page="page.currentPage" v-model:page-size="page.pageSize"
             v-model:total="page.totalResult"
             :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
             @page-change='刷新数据({来自分页:true})'>
    <template #right>
      <img src="https://xuliangzhan_admin.gitee.io/vxe-table/static/other/img1.gif" height="34">
      <img src="https://xuliangzhan_admin.gitee.io/vxe-table/static/other/img1.gif" height="34">
      <img src="https://xuliangzhan_admin.gitee.io/vxe-table/static/other/img1.gif" height="34">
    </template>
  </vxe-pager>

  <div>
    <!--    keep-source-->
    <vxe-table  border resizable show-overflow ref="xTable" :data="tableData"
               :edit-config="{trigger: 'click', mode: 'cell',showStatus: true}" size="small" :loading="加载中"
               @edit-closed="保存修改行" @edit-actived="记录编辑前"
               row-id="id"

    >
      <vxe-column type="checkbox" width="40"  ></vxe-column>
      <vxe-table-column type="seq" width="60" title="序号"></vxe-table-column>
      <vxe-table-column field="设备名称2" title="设备名2" width="110px"
                        :edit-render="{name: 'input', attrs: {type: 'text', placeholder: ''}}"
                        sortable></vxe-table-column>
      <vxe-table-column field="账号开关" title="分配" width="70" sortable>
        <template #default="{ row }">
          <showSelect v-model:number="row.账号开关" @change=" 保存修改行({row})"></showSelect>
        </template>
      </vxe-table-column>
      <vxe-table-column field="账号标记" title="标记" width="100" sortable
                        :edit-render="{name: 'input',attrs: {type: 'text', placeholder: ''}}"></vxe-table-column>
      <vxe-table-column field="账号" title="账号" width="120" sortable
                        ></vxe-table-column>
      <vxe-table-column field="密码" title="密码" width="200"
                        :edit-render="{name: 'input',attrs: {type: 'text', placeholder: ''}}"></vxe-table-column>
      <vxe-table-column field="vip" title="vip" width="70" sortable></vxe-table-column>
      <vxe-table-column field="元宝" title="元宝" width="165" sortable>
        <template #header>
          元宝(合计:{{单页元宝数量}})
        </template>
      </vxe-table-column>

<!--      <vxe-table-column field="账号状态" title="账号状态" width="110" sortable></vxe-table-column>-->
      <vxe-table-column field="日常完成" title="日常完成" width="110" sortable></vxe-table-column>
      <vxe-table-column field="已勾选多区数量" title="多区" width="110"  sortable>
        <template #default="{ row }" >
          <span>{{ row.已勾选多区数量 + "/" + row.多区总数量 }}</span>
          <vxe-button type="text" status="success" content="分配" @click="显示账号详情(row)"></vxe-button>
        </template>
      </vxe-table-column>
      <vxe-table-column field="账号状态" title="账号状态"
                        :edit-render="{name: 'input',attrs: {type: 'text', placeholder: ''}}" width="100"></vxe-table-column>
      <vxe-table-column field="script1" title="时间"  width="175" sortable></vxe-table-column>
      <vxe-table-column field="账号备注" title="备注" show-overflow width="230" :edit-render="{name: 'input',attrs: {type: 'text', placeholder: ''}}"></vxe-table-column>
    </vxe-table>
  </div>

  <vxe-modal v-model="账号详情_显示中" width="740" show-footer :title="账号详情_显示中账号" :destroy-on-close='true' :mask-closable="true" >
    <xszhxqf v-model:账号="账号详情_显示中账号"></xszhxqf>
  </vxe-modal>

</template>

<script>
import Moment from 'moment'
import fqxs from "../components/账号管理/分区管理";
import inputselect from "../components/输入搜索";
import showSelect from "../components/分配开关显示";
import xszhxqf from "../components/设备管理/显示账号下区服.vue";
import XEUtils from 'xe-utils'

export default {
  components: {fqxs, inputselect, showSelect, xszhxqf},
  data() {
    return {
      单页元宝数量:0,
      已勾选:[],
        搜索_账号: "",
        搜索_设备: "",
        搜索_多区: "",
        搜索_标记: "",
        搜索_分配: "",
        搜索_账号状态: "",
      搜索_区服状态: "",
      存储搜索条件:{},
      编辑原始值: "",
      账号详情_显示中: null,
      账号详情_显示中账号: null,
      加载中: true,
      多区数组: "",
      标记数组: "",
      分配数组: "",
      登录状态数组: "",
      区服状态数组: "",
      page: {
        currentPage: 1,
        pageSize: 100,
        totalResult: 0,
      },

      tableData: [],
    };
  },
  methods: {
    批量操作消息提示: async function (message1, message2="") {
      const table = this.getSelectionEvent();
      if (!table.length) {
        this.$XModal.confirm({content: message1, status: 'question', maskClosable: true});
        return false;
      }
      if(message2){
        var state = await this.$XModal.confirm(message2)
        if (state == 'cancel' || state=='close') {
          return false;
        }
      }
      this.已勾选=table;
      return table;
    },
    formatTime ({ cellValue, row, column }) {
      return XEUtils.toDateString(cellValue, 'yyyy-MM-dd HH:ss:mm')
    },
    发送请求: async function(){
      console.log('发送请求');
    },
    搜索账号列表: function () {
      var T = this
      T.page.currentPage = 1;
      var pageInfo = this.page;
      var 分配=T.搜索_分配;
      if(分配=='全部'){
        T.搜索_分配="";
      }else if(分配=='已分配'){
        T.搜索_分配=1
      }else if(分配=='未分配'){
        T.搜索_分配=2
      }
      var params = {
        账号: T.搜索_账号.trim(),
        设备名称: T.搜索_设备.trim(),
        区服名称: T.搜索_多区.trim(),
        账号标记: T.搜索_标记.trim(),
        账号开关: T.搜索_分配,
        账号状态: T.搜索_账号状态.trim(),
        区服状态: T.搜索_区服状态.trim(),
        第几页: pageInfo.currentPage,
        每页显示条数: pageInfo.pageSize
      }
      T.存储搜索条件=params
      T.tableData = [];
      T.已勾选=[]
      T.刷新数据(params);
    },
    显示账号详情: function (row) {
      this.账号详情_显示中账号 = row.账号;
      this.账号详情_显示中 = true;
    },

    focusEvent1() {
      this.$refs.xDown1.showPanel();
    },
    刷新数据:async function(params={}) {
      let T = this;
      if(params.来自分页){
        T.已勾选=[] //清空掉勾选
      }
      this.tableData = [];
      this.加载中 = true;
      let conditon=T.存储搜索条件
      this.$请求(
          "/rootnumber/list",
          {
            账号: conditon.账号,
            设备名称: conditon.设备名称,
            区服名称:  conditon.区服名称,
            账号标记:  conditon.账号标记,
            账号开关:  conditon.账号开关,
            账号状态:  conditon.账号状态,
            区服状态:  conditon.区服状态,
            第几页: T.page.currentPage,
            每页显示条数: T.page.pageSize,
          },
          function (response) {
            T.加载中 = false;
            T.tableData = response.data.data;
            T.单页元宝数量= response.data.data.reduce(function (preValue, n) {
               return preValue + n.元宝
            }, 0);
            T.$refs.xTable.setCheckboxRow( T.已勾选,true)
            T.page.totalResult = response.data.total;
            //T.$XModal.message({content: "刷新成功", status: "success"});
          },
          function () {
          }
      );
    },
    editClosedEvent({row, column}) {
      console.log(`${column.property} : ${row[column.property]}`);
    },

    getSelectionEvent: function () {
      const $table = this.$refs.xTable.getCheckboxRecords();
      return $table;
    },
    获取选中的账号和指定字段(字段) {
      //   this.加载中 = true;
      const table = this.getSelectionEvent();
      let tab = [];
      for (var i = 0; i < table.length; i++) {
        tab.push({账号: table[i].账号, [字段]: table[i][字段]});
      }
      return tab;
    },
    刷新当前页:async function(){
      const T=this;
      T.刷新数据();
    },

    删除选中: async function () {
      const table = await this.批量操作消息提示('请勾选需要删除的账号', '您确定要删除吗？')
      if (!table) {
        return;
      }
      this.加载中 = true;
      const T = this;
      let tab = [];
      for (var i = 0; i < table.length; i++) {
        tab.push(table[i].账号);
      }
      this.$请求(
          "/delete/allrootnumber",
          {
            账号数组: JSON.stringify(tab),
          },
          function (response) {
            T.刷新数据();
            T.$XModal.alert({content: "success 删除成功", status: "success"});
          },
          function (response) {
            alert("出错啦");
          }
      );
    },
    open(表头, 提示信息, thenfunc) {
      this.$prompt(提示信息, 表头, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        // inputPattern:/[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
        // inputErrorMessage: "邮箱格式不正确",
      })
          .then(
              thenfunc
              // ({ value }) => {
              //   this.$message({
              //     type: "success",
              //     message: "你的邮箱是: " + value,
              //   });
              // }
          )
          .catch(() => {
            this.$message({
              type: "info",
              message: "取消输入",
            });
          });
    },
    批量修改_上传: function (data) {
      this.加载中 = true;
      const 地址 = "/batchEdit";
      const 数据 = {账号批量修改: JSON.stringify(data)};
      const success = (response) => {
        this.加载中 = false;
        this.$XModal.message();
        this.刷新数据();
      };
      const error = (response) => {
        this.$XModal.message({content: "修改失败", status: "error"});
      };
      this.$请求(地址, 数据, success, error);
    },
    批量修改_标记: async function () { //已解
      // 决
      const table = await this.批量操作消息提示('请勾选需要批量修改标记的账号')
      if (!table) {
        return;
      }
      var ids = table.map(x => x.id);
      var T = this;
      var data = T.tableData;
      this.open("修改标记", "请输入标记", ({value}) => {
        var newData = []
        for (let i = 0; i < data.length; i++) {
          if (ids.includes(data[i].id)) {
            newData.push({id: data[i].id, 账号标记: value})
          }
        }
        this.批量修改_上传(newData);
      });
    },
    批量修改_设备名2: async function () {
      const table = await this.批量操作消息提示('请勾选需要批量设定设备名2的账号')
      if (!table) {
        return;
      }
      this.open("修改设备", "请输入设备名2", ({value}) => {
        let tab = [];
        for (var i = 0; i < table.length; i++) {
          tab.push({id: table[i].id, 设备名2: value});
        }
        this.批量修改_上传(tab);
      });
    },
    批量修改_启动分配: async function () {
      const table = await this.批量操作消息提示('请勾选需要启动分配的账号')
      if (!table) {
        return;
      }
      var ids = table.map(x => x.id);
      var T = this;
      var data = T.tableData;
      var newData = []
      for (let i = 0; i < data.length; i++) {
        if (ids.includes(data[i].id)) {
          T.tableData[i].账号开关 = 1;
          newData.push({id: data[i].id, 账号开关: 1})
        }
      }
      T.批量修改_上传(newData);
    },
    批量修改_取消分配:async function () {
      const table = await this.批量操作消息提示('请勾选需要取消分配的账号')
      if (!table) {
        return;
      }
      var ids = table.map(x => x.id);
      var T = this;
      var data = T.tableData;
      var newData = []
      for (let i = 0; i < data.length; i++) {
        if (ids.includes(data[i].id)) {
          newData.push({id: data[i].id, 账号开关: 2})
        }
      }
      // 上传
      this.批量修改_上传(newData);
    },
    批量修改_恢复账号状态: async function () {
      const table = await this.批量操作消息提示('请勾选需要恢复状态的账号')
      if (!table) {
        return;
      }
      var ids = table.map(x => x.id);
      var T = this;
      var data = T.tableData;
      var newData = []
      for (let i = 0; i < data.length; i++) {
        if (ids.includes(data[i].id)) {
          newData.push({id: data[i].id, 账号状态: '正常'})
        }
      }
      // 上传
      this.批量修改_上传(newData);
    },
    保存打钩项: function () {
      const table = this.getSelectionEvent();
      const table2 = JSON.parse(JSON.stringify(table));
      const T = this;

      for (var i = 0, new_data = []; i < table2.length; i++) {
        delete table2[i]._XID;
      }
      this.$axios
          .post(this.$route.query.admin + "/账号修改all", {
            data: JSON.stringify(table2),
          })
          .then(function (response) {
            console.log(response.data);
            T.刷新数据();
            T.$XModal.alert({content: "success 保存成功", status: "success"});
          })
          .catch(function (error) {
            alert("出错啦");
          });
    },

    导出到文档: async function () {
      const table = await this.批量操作消息提示('请勾选需要导出的账号')
      if (!table) {
        return;
      }
      var idArr = table.map(x => x.id);
      this.$请求('/export/rootnumber',{idArr},function (obj){
        var content=obj.data;
        var urlObject = window.URL || window.webkitURL || window;
        var export_blob = new Blob([content]);
        var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
        save_link.href = urlObject.createObjectURL(export_blob);
        var name=Moment().format("YYYY-MM-DD HH:mm:ss");
        save_link.download = '账号_'+name;
        save_link.click();
      })
      // const $table = this.$refs.xTable;
      // $table.exportData({
      //   data: $table.getCheckboxRecords(),
      // });
    },
    记录编辑前: function ({row, column}) {
      this.编辑原始值 = row[column.property]
    },
    保存修改行({row, column}) {
      if (column) {
        if (row[column.property] == this.编辑原始值) {
          console.log('-------------');
          return
        }
      }
      let data = {
        账号: row.账号,
        设备名称: row.设备名称,
        设备名称2: row.设备名称2,
        账号开关: row.账号开关,
        账号标记: row.账号标记,
        密码: row.密码,
        账号备注: row.账号备注,
        账号状态: row.账号状态,
      }
      this.加载中 = true;
      let T = this;
      this.$请求(
          "/update/rootnumber/info",
          data,
          function (obj) {
            T.加载中 = false;
            if (obj && obj.data.code !== 1) {
              T.$XModal.alert({content: `修改失败:${obj.data.message}`, status: 'error'})
            }
          },
          function (err) {
            console.log(err);
          }
      );
    },
    //--------------------------------------------------批量的方法
    清空多区分配: async function () {
      var table = await this.批量操作消息提示('请勾选需要清空多区分配的账号', "确定要清空多区分配");
      if (!table) {
        return;
      }
      const T = this;
      let tab = [];
      for (var i = 0; i < table.length; i++) {
        tab.push(table[i].账号);
      }
      const tableString = JSON.stringify(tab);
      T.加载中 = true;
      this.$请求(
          '/clear/duoqu/fenpei',
          {账号数组: tableString},
          (obj) => {
            T.加载中 = false;
            if (obj.data.code !== 1) {
              T.$XModal.message({content: `${obj.data.message}`, status: 'error'});
              return;
            }
            T.$XModal.message({content: '清空多区分配成功', status: 'success'});
            T.刷新数据();
          },
          (err) => {
            console.log(err);
          }
      )
    },

    移除指定区分配: async function () {
      var T = this;
      var table = await this.批量操作消息提示('请勾账号');
      if (!table) {
        return;
      }
      this.open("移除区服", "请输入需要移除的区服名称", ({value}) => {
        let tab = [];
        for (var i = 0; i < table.length; i++) {
          tab.push(table[i].账号);
        }
        tab = JSON.stringify(tab);
        T.加载中 = true;
        T.$请求('/remove/assign/area', {账号数组: tab, 区服名称: value},
            function (obj) {
              T.加载中 = false;
              if (obj.data.code !== 1) {
                T.$XModal.message({content: `${obj.data.message}`, status: 'error'});
                return;
              }
              T.$XModal.message({content: '移除指定区成功', status: 'success'});
              T.刷新数据();
            },
            function (error) {
              console.log(error);
            }
        )
      });
    },

    开启关闭指定区:async function (event) {
      var T = this;
      var 区服开关=event.$event.currentTarget.getAttribute("value");
      var table = await this.批量操作消息提示('请勾账号');
      if (!table) {
        return;
      }

      this.open(区服开关==1?"开启指定区服":"关闭指定区服", "请输入指定区服名称", ({value}) => {
        let tab = [];
        for (var i = 0; i < table.length; i++) {
          tab.push(table[i].账号);
        }
        tab = JSON.stringify(tab);
        T.加载中 = true;
        T.$请求('/openclose/area', {账号数组: tab, 区服名称: value,区服开关},
            function (obj) {
              T.加载中 = false;
              if (obj.data.code !== 1) {
                T.$XModal.message({content: `${obj.data.message}`, status: 'error'});
                return;
              }
              T.$XModal.message({content: '成功', status: 'success'});
              T.刷新数据();
            },
            function (error) {
              console.log(error);
            }
        )
      });
    },

    开启关闭_全部区:async function (event) {
      var T = this;
      var 区服开关=event.$event.currentTarget.getAttribute("value");
      var table = await this.批量操作消息提示('请勾账号');
      if (!table) {
        return;
      }
      let tab = [];
      for (var i = 0; i < table.length; i++) {
        tab.push(table[i].账号);
      }
      tab = JSON.stringify(tab);
      T.加载中 = true;
      T.$请求('/openclose/all/area', {账号数组: tab, 区服开关},
          function (obj) {
            T.加载中 = false;
            if (obj.data.code !== 1) {
              T.$XModal.message({content: `${obj.data.message}`, status: 'error'});
              return;
            }
            T.$XModal.message({content: '成功', status: 'success'});
            T.刷新数据();
          },
          function (error) {
            console.log(error);
          }
      )

    },

    分配多区_拼接:async function () {
      var T = this;
      var table = await this.批量操作消息提示('请勾账号');
      if (!table) {
        return;
      }
      this.open("输入多个区服用+号拼接", "例如: 骷髅洞+赤月1+赤月2", ({value}) => {
        let tab = [];
        for (var i = 0; i < table.length; i++) {
          tab.push(table[i].账号);
        }
        tab = JSON.stringify(tab);
        T.加载中 = true;
        T.$请求('/batch/deal/area', {账号数组: tab, 字符串: value},
            function (obj) {
              T.加载中 = false;
              T.刷新数据();
            },
            function (error) {
              console.log(error);
            }
        )
      });
    },
    获取下拉框数据:async function(){
      const T=this;
      this.$请求(
          '/get/select/qufu/name',
          {},
          function (obj) {
            if (!(obj && obj.data.code == 1)) {
              // T.$XModal.message({content: "获取下来框数据失败", status: "error"})
              console.log('获取下来框数据失败');
              return;
            }
            var data = obj.data.data;
            var arr = []
            var arr_标记 = []
            var arr_账号登录状态数组 = []
            var arr_区服状态数组 = []
            data.areaNameArr.forEach(function (v) {
              if (v.区服名称) {
                arr.push({label:v.区服名称,number:v.number});
              }
            })
            data.markArr.forEach(function (v) {
              if (v.账号标记) {
                arr_标记.push({label:v.账号标记,number:v.number});
              }
            })
            data.loginState.forEach(function (v) {
              if (v.账号状态) {
                arr_账号登录状态数组.push({label:v.账号状态});
              }
            })
            data.qufuState.forEach(function (v) {
              if (v.区服状态) {
                arr_区服状态数组.push({label:v.区服状态});
              }
            })
            T.多区数组 = arr;
            T.标记数组 = arr_标记;
            T.登录状态数组 = arr_账号登录状态数组;
            T.区服状态数组 = arr_区服状态数组;
          },
          function (err) {

          }
      )
    }

  },
  created() {
    this.刷新数据();
    this.获取下拉框数据()
  },
  watch:{
    page:{//深度监听，可监听到对象、数组的变化
      handler(val, oldVal){
        console.log('深度监听，可监听到对象、数组的变化');
        console.log("page.currentPage: "+val.currentPage, oldVal.currentPage);
      },
      deep:true //true 深度监听
    }
  }
};
</script>

<style scoped>

button {
  margin: 1px !important;
  border: 0px !important;
  /* padding: px !important; */
}

.my-domain{
  width: 170px;
}

</style>
